<!--
  * 项目列表
-->
<template>
  <a-form class="smart-query-form" v-privilege="'project:query'">
    <a-row class="smart-query-form-row">
      <a-form-item label="项目名称" class="smart-query-form-item" name="name">
        <a-input style="width: 300px" v-model:value="queryForm.name" placeholder="请输入项目名称" />
      </a-form-item>
      <a-form-item label="上级项目" class="smart-query-form-item">
       <ProjectSelectTree  v-model:value="queryForm.parentId"  width="260px" />
      </a-form-item>
      <a-form-item label="项目类型" name="type" class="smart-query-form-item">
        <DictSelectType :service-id="SERVICE_ID_ENUM.DICTIONARY.value" :dcit-type="DICT_TYPE_ENUM.PROJECT_TYPE.value" v-model:value="queryForm.type" width="120px" />
      </a-form-item>

      <a-form-item label="项目状态" name="state" class="smart-query-form-item">
        <DictSelectType :service-id="SERVICE_ID_ENUM.DICTIONARY.value" :dcit-type="DICT_TYPE_ENUM.STATE.value" v-model:value="queryForm.state" width="120px" />
      </a-form-item>
      <a-form-item label="采集阶段" name="collectState" class="smart-query-form-item">
        <DictSelectType :service-id="SERVICE_ID_ENUM.DICTIONARY.value" :dcit-type="DICT_TYPE_ENUM.PROJECT_COLLECT_STATE.value" v-model:value="queryForm.collectState" width="120px" />
      </a-form-item>

      
      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="ajaxQuery">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false" :hoverable="true">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="add()" v-privilege="'project:add'" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新建项目
        </a-button>
        <a-button @click="stateUpdate()" v-privilege="'project:stateUpdate'" type="primary" size="small">
          <template #icon>
            <FormOutlined />
          </template>
          状态变更
        </a-button>
        <a-button @click="approval()" v-privilege="'project:collectState'" type="primary" size="small">
          <template #icon>
            <CheckOutlined />
          </template>
          采集阶段变更
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.TASK.PROJECT_INFO" :refresh="ajaxQuery" />
      </div>
    </a-row>

    <a-table
      :scroll="{ x: 1300 }"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      :pagination="false"
      :loading="tableLoading"
      bordered
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'name'">
          <a @click="detail(record.id)">{{ text }}</a>
        </template>
        <template v-if="column.dataIndex === 'planBegin'">
          <span>{{ dayjs(text).format("YYYY-MM-DD") }}</span>
        </template>
        <template v-if="column.dataIndex === 'planEnd'">
          <span>{{ dayjs(text).format("YYYY-MM-DD") }}</span>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button v-if=" record.state===0 " @click="update(record)" v-privilege="'project:edit'" type="link">编辑</a-button>
            <a-button v-if=" record.state===0 " @click="confirmDelete(record.id)" danger v-privilege="'project:delete'" type="link">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageIndex"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="ajaxQuery"
        @showSizeChange="ajaxQuery"
        :show-total="(total) => `共${total}条`"
      />
    </div>
    <TaskOperate ref="operateRef" @refresh="ajaxQuery" />
    <UpdateFormModal ref="updateFormModal" @refresh="ajaxQuery" />
  </a-card>
</template>
<script setup lang="ts">
  import { reactive, ref, onMounted,computed } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { projectApi } from '/@/api/task/project-api';
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { useRouter } from 'vue-router';
  import TaskOperate from './components/project-operate-modal.vue';
  import UpdateFormModal from './components/update-batch-form-modal.vue';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
  import { SERVICE_ID_ENUM,DICT_TYPE_ENUM } from '/@/constants/system/cache-service-id-const';
  import DictSelectType from '/@/components/cache/dict-select-type.vue'
  import ProjectSelectTree from '/@/components/business/task/project-select-tree.vue';

  // --------------------------- 企业表格 列 ---------------------------

  const columns = ref([
    {
      title: '项目名称',
      dataIndex: 'name',
      //width: 280,
      ellipsis: true,
    },
    {
      title: '上级项目名称',
      dataIndex: 'parentName',
      //width: 250,
      ellipsis: true,
    },
    {
      title: '项目简称',
      dataIndex: 'shortName',
      width: 100,
      ellipsis: true,
    },
    {
      title: '负责人',
      dataIndex: 'implementerName',
      width: 80,
    },
    {
      title: '项目类型',
      dataIndex: 'typeName',
      width: 80,
    },
    {
      title: '计划开始',
      width: 100,
      dataIndex: 'planBegin',
      ellipsis: true,
    },
    {
      title: '计划结束',
      width: 100,
      dataIndex: 'planEnd',
      ellipsis: true,
    },
    {
      title: '采集阶段',
      width: 80,
      dataIndex: 'collectStateName',
      ellipsis: true,
    },
    {
      title: '项目状态',
      width: 80,
      dataIndex: 'stateName',
      ellipsis: true,
    },
    {
      title: '业务人员',
      width: 80,
      dataIndex: 'businessImplementerName',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 100,
    },
  ]);

  // --------------------------- 查询 ---------------------------

  const queryFormState = {
    name: undefined,
    type: undefined,
    parentId: undefined,
    implementer: undefined,
    planBeginStart: undefined,
    planBeginEnd: undefined,
    collectState: undefined,
    state: undefined,
    pageIndex: 1,
    pageSize: PAGE_SIZE,
  };
  const queryForm = reactive({ ...queryFormState });
  const tableLoading = ref(false);
  const tableData = ref([]);
  const total = ref(0);
  const planBegin=ref([]);

    let selectedRowKeys = ref([]);
    let selectedRows = ref([]);
    // 是否有选中：用于 批量操作按钮的禁用
    const hasSelected = computed(() => selectedRowKeys.value.length > 0);

    function onSelectChange(keyArray, selectRows) {
      selectedRowKeys.value = keyArray;
      selectedRows.value = selectRows;
    }

    function dateChange(dates, dateStrings) {
    queryForm.planBeginStart = dateStrings[0];
    queryForm.planBeginEnd = dateStrings[1];
  }


  function resetQuery() {
    Object.assign(queryForm, queryFormState);
    planBegin.value=[];
    ajaxQuery();
  }

  async function ajaxQuery() {
    try {
      tableLoading.value = true;
      let responseModel = await projectApi.pageQuery(queryForm);
      if(responseModel.success){
        const list = responseModel.data.data;
        total.value = responseModel.data.total;
        tableData.value = list;

         selectedRowKeys.value = [];
         selectedRows.value = [];
      }else
        message.error(responseModel.message);
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  // --------------------------- 删除 ---------------------------

  function confirmDelete(projectId) {
    Modal.confirm({
      title: '确定要删除吗？',
      content: '删除后，该信息将不可恢复',
      okText: '删除',
      okType: 'danger',
      onOk() {
        del(projectId);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function del(projectId) {
    try {
      SmartLoading.show();
      await projectApi.delete(projectId);
      message.success('删除成功');
      ajaxQuery();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // --------------------------- 增加、修改、详情 ---------------------------

    const updateFormModal =ref();

   function approval(){
   if (!hasSelected.value) {
         message.warning('请选择要变更的项目');
         return;
       }
       const taskIdArray = selectedRows.value.map((e) => e.id);
       updateFormModal.value.showModal(taskIdArray,false);
   }

   function stateUpdate(){
      if (!hasSelected.value) {
            message.warning('请选择要变更的项目');
            return;
          }
          const projectIdArray = selectedRows.value.map((e) => e.id);
          updateFormModal.value.showModal(projectIdArray,true);
      }

  let router = useRouter();
  const operateRef = ref();
  function add() {
    operateRef.value.showModal();
  }

  function update(record) {
    operateRef.value.showModal(record);
  }

  function detail(projectId) {
    router.push({ path: '/tm/project/detail', query: { projectId: projectId } });
  }

  onMounted(ajaxQuery);
</script>
